package fr.rosetti.formulaires;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.RuntimeExceptionDao;

import fr.rosetti.database.DatabaseHelper;
import fr.rosetti.macarte.PlaceActivity;
import fr.rosetti.macarte.R;
import fr.rosetti.model.Arbre;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class TreeForm extends Activity {
	
	private EditText name;
	private Spinner type;
	private Button save;
	private Button cancel;
	private DatabaseHelper databaseHelper;
	private RuntimeExceptionDao<Arbre, Integer> arbreDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tree_form);
		initForm();
		// get our dao
		arbreDao = getHelper().getArbreDao();

	}
	
	private DatabaseHelper getHelper() {
		if (databaseHelper == null) {
	        databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
	    }
	    return databaseHelper;
	}
	
	@Override
	protected void onDestroy() {
	    super.onDestroy();
	    if (databaseHelper != null) {
	        OpenHelperManager.releaseHelper();
	        databaseHelper = null;
	    }
	}

	private void initForm() {
		name = (EditText)findViewById(R.id.editText1);
		type = (Spinner)findViewById(R.id.spinner1);
		save =(Button)findViewById(R.id.button1);
		cancel = (Button)findViewById(R.id.button2);
		// Create an ArrayAdapter using the string array and a default spinner layout
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.type_arbre, android.R.layout.simple_dropdown_item_1line);
		// Specify the layout to use when the list of choices appears
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// Apply the adapter to the spinner
		type.setAdapter(adapter);
		
		save.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Arbre arbre = new Arbre(name.getText().toString(),type.getSelectedItem().toString(),
						getIntent().getDoubleExtra("lat", 0),getIntent().getDoubleExtra("lng", 0));
				arbreDao.createOrUpdate(arbre);
				Intent intent = new Intent(TreeForm.this,PlaceActivity.class);
				intent.putExtra("id_arbre",arbre.getId());
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		
		cancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});
	}

}
